import 'dart:async';

import 'package:deepseek_client/common/EventBus.dart';
import 'package:deepseek_client/common/db/DbManager.dart';
import 'package:deepseek_client/common/event/event.dart';
import 'package:flutter/material.dart';

import '../common/db/ConversationWrapper.dart';

class MainLeftDrawer extends StatefulWidget {
  // 添加 bool 属性来控制宽度的开启和关闭
  final bool isOpen;

  const MainLeftDrawer({super.key, required this.isOpen});

  @override
  State<StatefulWidget> createState() => _MainLeftDrawerState();
}

class _MainLeftDrawerState extends State<MainLeftDrawer>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _widthAnimation;
  late bool _isOpen;
  final ValueNotifier<List<ConversationWrapper>> _conversationNotifier =
      ValueNotifier([]);
  StreamSubscription? _updateTask;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _isOpen = widget.isOpen;
    _widthAnimation = Tween<double>(begin: 0, end: 200).animate(_controller)
      ..addListener(() {
        setState(() {});
      });
    if (_isOpen) {
      _controller.forward();
    } else {
      _controller.reverse();
    }

    _loadHistoryConversations();
    _updateTask = eventBus.on<UpdateConversationHistoryEvent>().listen((_) {
      _loadHistoryConversations();
    });
  }

  _loadHistoryConversations() async {
    var historyConversations = await database?.conversationDao.findAllConversation();
    _conversationNotifier.value = historyConversations ?? [];
  }

  @override
  void didUpdateWidget(MainLeftDrawer oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.isOpen && !oldWidget.isOpen) {
      _controller.forward();
    } else if (!widget.isOpen && oldWidget.isOpen) {
      _controller.reverse();
    }
  }

  @override
  void dispose() {
    _updateTask?.cancel();
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: _widthAnimation.value,
      height: double.infinity,
      clipBehavior: Clip.hardEdge,
      decoration: const BoxDecoration(
        border: BorderDirectional(end: BorderSide(
          width: 1,
          color: Color(0xFFF2F2F2),
        ))
      ),
      child: SizedBox(
        width: 200,
        height: double.infinity,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Flexible(child: ValueListenableBuilder(
                valueListenable: _conversationNotifier,
                builder: (context, list, child) {
                  if(list.isEmpty){
                    return const Center(
                      child:  Text(
                        "暂无历史会话~",
                        maxLines: 1,
                        style: TextStyle(fontSize: 16, color: Color(0xFF999999) , fontWeight: FontWeight.w600),
                      ),
                    );
                  }
                  return ListView.builder(
                    itemBuilder: (context, index) {
                      var item = list[index];
                      return InkWell(
                        onTap: () async {
                          eventBus.fire(OnHistoryItemTapEvent(conversation: item));
                          eventBus.fire(CollapseHistoryEvent());
                        },
                        child: Padding(
                          padding: const EdgeInsets.only(left: 20, right: 20),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const SizedBox(
                                height: 5,
                              ),
                              Text(
                                item.title,
                                style: const TextStyle(
                                    color: Color(0xFF141414), fontSize: 16),
                                maxLines: 1,
                              ),
                              Text(
                                item.createTime,
                                style: const TextStyle(
                                    color: Color(0xFFAAAAAA), fontSize: 12),
                                maxLines: 1,
                              ),
                              const SizedBox(
                                height: 5,
                              ),
                              Container(
                                height: 1,
                                color: const Color(0xFFF2F2F2),
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                    shrinkWrap: false,
                    itemCount: list.length,
                  );
                })),
            const SizedBox(
              height: 20,
            ),
            MouseRegion(
              cursor: SystemMouseCursors.click,
              child: GestureDetector(
                onTap: () async {
                  await database?.conversationDao.deleteAllConversation();
                  eventBus.fire(HistoryClearEvent());
                  _loadHistoryConversations();
                },
                child: Container(
                  height: 32,
                  padding: const EdgeInsets.only(left: 10 , right: 10 , top: 5 , bottom: 5),
                  decoration: BoxDecoration(
                    color: const Color(0xFFEEEEEE),
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: const Text("清空历史" , style: TextStyle(
                    color: Color(0xFF141414),
                  ),),
                ),
              ),
            ),
            const SizedBox(
              height: 40,
            )
          ],
        ),
      ),
    );
  }
}
